package com.star.spring.deferred.service.thread.safe;


import com.star.spring.deferred.utils.CommonUtils;

/**
 * @description: 同步锁
 * @author: star
 * @create: 2025-01-01 23:24
 **/

public class SynchronizeDemo {

    static private int result = 0;
    static Object lock1 = new Object();
    static Object lock2 = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (lock1) {
                    result++;

                }
            }
        }, "t1");

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (lock2) {
                    result--;
                }
            }
        }, "t2"
        );

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();
        CommonUtils.log("result = " + result);
    }
}
